﻿using Dapper;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace NewBee.Core.Data.SQLBuilder
{
    public class Sql
    {
        #region Class Members

        /// <summary>
        /// DB 帮助对象
        /// </summary>
        private DbHelper _DbHeler;
        /// <summary>
        /// 查询语句
        /// </summary>
        private string _SqlString;
        /// <summary>
        /// 参数集合
        /// </summary>
        private object _Parameter;
        private DynamicParameters _Parameters = new DynamicParameters();
        #endregion

        #region Constructors

        /// <summary>
        /// 初始化构造器
        /// </summary>
        /// <param name="dbHelper">DB 帮助对象</param>
        /// <param name="sqlString">查询语句</param>
        public Sql(DbHelper dbHelper, string sqlString)
        {
            _DbHeler = dbHelper;
            _SqlString = sqlString;
        }

        #endregion

        #region Methods

        /// <summary>
        /// 初始化参数集合
        /// </summary>
        /// <param name="parameters">所需参数集合</param>
        /// <returns></returns>
        public Sql Parameter(object parameter)
        {
            _Parameter = parameter;
            return this;
        }
        /// <summary>
        /// 条件中的参数
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public Sql Parameters(params object[] parameters)
        {
            if (parameters != null)
            {
                for (var i = 0; i < parameters.Length; i++)
                {
                    _Parameters.Add("@" + i, parameters[i]==null? 0: parameters[i]);
                }
            }

            return this;
        }
        /// <summary>
        /// 执行 SQL 语句
        /// 一般用于 Insert、Delete、Update 操作
        /// </summary>
        /// <returns>受影响的行数</returns>
        public int Execute()
        {
            return _DbHeler.Execute(_SqlString, _Parameter==null?_Parameters: _Parameter);
        }

        /// <summary>
        /// 查询多条结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IEnumerable<T> Query<T>()
        {
            return _DbHeler.Query<T>(_SqlString, _Parameter == null ? _Parameters : _Parameter);
        }

        /// <summary>
        /// 查询结果个数
        /// </summary>
        /// <returns></returns>
        public int Count()
        {
            return _DbHeler.Query<int>(_SqlString, _Parameter == null ? _Parameters : _Parameter).FirstOrDefault();
        }
        
        #endregion
    }
}
